const { exiftool } = require('exiftool-vendored');
const fs = require('fs-extra');
const path = require('path');
const dayjs = require('dayjs');
const customParseFormat = require('dayjs/plugin/customParseFormat');

dayjs.extend(customParseFormat);

// 解析文件名中的时间戳
function extractTimestamp(filename) {
    const regexList = [
        /^(\d{4})-(\d{2})-(\d{2})\.mp4$/i, // 2020-02-05.mp4
        /^HnVideoEditor_(\d{4})_(\d{2})_(\d{2})_(\d{2})(\d{2})(\d{2})(\d{3})\.mp4$/i,
        /^lv_\d+_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.mp4$/i,
        /^lv_\d+_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/i,
        /^(mv|MV)_(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\.mp4$/i,
        /^VID_(\d{8})_(\d{6})\.mp4$/i, // VID_20170827_162355.mp4
        /^TG-(\d{4})-(\d{2})-(\d{2})-\d+\.mp4$/i,
        /^VIDEO_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})(\d{3})\.mp4$/i,
        /^(\d{13})\.mp4$/i,
        /^mmexport(\d{13})\.mp4$/i,
        /^wx_camera_(\d{13})\.mp4$/i
    ];

    for (const regex of regexList) {
        const match = filename.match(regex);
        if (match) {
            console.log('Matched regex:', regex); // 输出匹配的正则表达式
            const regexString = regex.toString();

            // 使用字符串进行比较
            if (regexString === /^VID_(\d{8})_(\d{6})\.mp4$/i.toString()) {
                const datePart = match[1]; // 20200429
                const timePart = match[2]; // 190858
                const year = datePart.substring(0, 4);
                const month = datePart.substring(4, 6);
                const day = datePart.substring(6, 8);
                const hour = timePart.substring(0, 2);
                const minute = timePart.substring(2, 4);
                const second = timePart.substring(4, 6);
                return [year, month, day, hour, minute, second];
            } else if (regexString === /^(\d{13})\.mp4$/i.toString() ||
                regexString === /^mmexport(\d{13})\.mp4$/i.toString() ||
                regexString === /^wx_camera_(\d{13})\.mp4$/i.toString()) {
                // 处理毫秒级 Unix 时间戳
                return [parseInt(match[1], 10)];
            }
            return match.slice(1); // 返回匹配到的所有时间部分
        }
    }
    return null;
}

// 将文件名中的时间戳转换为标准日期格式
function formatTimestamp(timestampParts) {
    if (timestampParts.length === 1) {
        // Unix 毫秒时间戳
        return dayjs(timestampParts[0]).format('YYYY:MM:DD HH:mm:ss');
    } else if (timestampParts.length === 3) {
        // 形如 [年, 月, 日]
        return dayjs(`${timestampParts[0]}-${timestampParts[1]}-${timestampParts[2]}`, 'YYYY-MM-DD').format('YYYY:MM:DD HH:mm:ss');
    } else if (timestampParts.length === 6) {
        // 形如 [年, 月, 日, 时, 分, 秒]
        return dayjs(`${timestampParts[0]}-${timestampParts[1]}-${timestampParts[2]} ${timestampParts[3]}:${timestampParts[4]}:${timestampParts[5]}`, 'YYYY-MM-DD HH:mm:ss').format('YYYY:MM:DD HH:mm:ss');
    } else if (timestampParts.length === 7) {
        // 形如 [年, 月, 日, 时, 分, 秒, 毫秒]
        return dayjs(`${timestampParts[0]}-${timestampParts[1]}-${timestampParts[2]} ${timestampParts[3]}:${timestampParts[4]}:${timestampParts[5]}.${timestampParts[6]}`, 'YYYY-MM-DD HH:mm:ss.SSS').format('YYYY:MM:DD HH:mm:ss');
    }
    return null;
}

// 处理视频的EXIF修改
async function processImage(filePath) {
    try {
        const metadata = await exiftool.read(filePath);
        const filename = path.basename(filePath);
        const timestampParts = extractTimestamp(filename);

        if (!timestampParts) {
            console.log(`No timestamp found in file name: ${filename}`);
            return false;
        }

        const formattedTimestamp = formatTimestamp(timestampParts);
        const exifDate = metadata.DateTimeOriginal;

        // 如果EXIF的创建时间与文件名中的时间不同，修改EXIF时间
        if (exifDate !== formattedTimestamp) {
            await exiftool.write(filePath, {
                DateTimeOriginal: formattedTimestamp,
                CreateDate: formattedTimestamp,
                ModifyDate: formattedTimestamp,
            }, ['-overwrite_original']);
            console.log(`Updated EXIF for: ${filename} - ${formattedTimestamp}`);
            return true;
        } else {
            console.log(`EXIF already up to date for: ${filename}`);
            return true;
        }
    } catch (error) {
        console.error(`Failed to process file: ${filePath}`, error);
        return false;
    }
}

// 递归遍历目录，处理所有文件
async function processDirectory(directoryPath) {
    const files = await fs.readdir(directoryPath);
    for (const file of files) {
        const filePath = path.join(directoryPath, file);
        const stats = await fs.stat(filePath);

        if (stats.isDirectory()) {
            await processDirectory(filePath);
        } else if (path.extname(file).toLowerCase() === '.mp4') {
            await processImage(filePath);
        }
    }
}

// 执行脚本主逻辑
async function main() {
    const folderPath = path.join(__dirname, '../videos'); // 替换为视频文件夹路径
    await processDirectory(folderPath);
    await exiftool.end();
}

main().catch(console.error);
